import os,time,re,sys
from threading import Thread
from MsgProcess import MsgProcess, MsgType
#解析文本
import plugin.Remind.todat_time_analysis as todat_time_analysis
#读取和保存闹钟
import plugin.Remind.write_read as write_read
#删除闹钟
import plugin.Remind.del_remind as del_remind 


#提醒
#支持多个提醒和语音取消提醒
#支持自动删除过期提醒
#支持重启继续
#如果是每天的提醒那么用时间戳是不合适的

class Remind(MsgProcess):
        #重复
        #{0:[12,35,00,'起床']}
        #一次性
        #{1:[12345,'起床']}
    def Start(self, message):
        time.sleep(10)
        self.key =0
        self.root_path = os.path.abspath(os.path.dirname(__file__))
        self.timelist=write_read.clock()#[]
        del_remind.del_remind(self.timelist,self.say,self.listen,be_overdue=True)
        #写入闹钟
        write_read.clock(self.timelist)
        #时间监听
        self.ti=Thread(target=self.while_time)
        self.ti.start()
        #响铃监听
        self.pl=Thread(target=self.play)
        self.pl.start()
        #显示监听
        self.vi=Thread(target=self.video)
        self.vi.start()
        
    #提醒时间到了,如果不唤醒一下,就会一直响铃.
    def play(self):
        while 1:
            time.sleep(0.2)
            if self.key ==1:
                os.system("aplay "+ os.path.join(self.root_path,"Remind.wav"))
    #前端显示
    def video(self):
        #key=0图标默认记录
        #key=1图标显示记录
        #key=2图标清空记录

        key = 0
        while 1:
            time.sleep(0.2)
            #没有提醒
            if not self.timelist:
                #清空操作只能一次
                if not key==2: 
                    time.sleep(2)
                    datas = {  "type":"exejs","data":"set_remind('{0}')".format("")   }
                    self.send( MsgType=MsgType.Text, Receiver="Screen", Data= datas )

                    datas = {  "type":"exejs","data":"ico_remind(2)"  }
                    self.send( MsgType=MsgType.Text, Receiver="Screen", Data= datas )
                    key =2
            #如果有提醒
            if self.timelist:
                #发送图标只能一次
                if key==0 or key==2:
                    datas = {  "type":"exejs","data":"ico_remind (1)"  }
                    self.send( MsgType=MsgType.Text, Receiver="Screen", Data= datas )
                    key=1

            say_dtat="未设置提醒服务"
            for y in  self.timelist:
                time.sleep(3)
                for x in y:
                    if int(x)==1:
                        say_dtat = "临时:"+time.strftime( "%Y-%m-%d %H点%M分%S秒", time.localtime(y[x][0]) ) + y[x][1]
                        say_dtat = say_dtat.replace("00分",'',1).replace("00秒",'',1)
                            
                    if int(x) ==0:
                        say_dtat = "每天:"+str(y[x][0])+"点"+str(y[x][1])+"分"+str(y[x][3])
                        say_dtat = say_dtat.replace("00分",'',1)
                    
                    datas = {  "type":"exejs","data":"set_remind('{0}')".format( say_dtat )   }
                    self.send( MsgType=MsgType.Text, Receiver="Screen", Data= datas )




    #时间监听
    def while_time(self):
        while 1:
            #扫描时间
            time.sleep(0.2)
            number =-1
            #总列表
            for x in self.timelist:
                number +=1
                #字典
                for  y in x:
                    if int(y)==0:
                        xs_xf_xm = time.time()
                        xs = time.strftime("%H", time.localtime(xs_xf_xm)) 
                        xf = time.strftime("%M", time.localtime(xs_xf_xm))
                        xm = time.strftime("%S", time.localtime(xs_xf_xm)) 

                        if int(xs) ==int(x[y][0]) and int(xf) ==int(x[y][1]) and int(xm) ==int(x[y][2]):
                            self.send(MsgType=MsgType.Text, Receiver="SpeechSynthesis", Data="闹钟"+x[y][3])
                            self.send(MsgType=MsgType.Text, Receiver="Screen", Data="闹钟"+x[y][3])
                            self.key = 1
                            time.sleep(1)#让这一秒过去,让条件不成立
                        
                           
                    if int(y)==1:
                        if int(time.time())==int(x[y][0]):
                            self.send(MsgType=MsgType.Text, Receiver="SpeechSynthesis", Data="闹钟"+x[y][1])
                            self.send(MsgType=MsgType.Text, Receiver="Screen", Data="闹钟"+x[y][1])
                            #print(self.timelist[number])
                            self.timelist.pop(number)
                            #print(self.timelist)
                            #写入闹钟
                            write_read.clock(self.timelist)
                            self.key = 1
                            time.sleep(1)#让这一秒过去,让条件不成立
                    

    #响铃时唤醒即可关闭响铃
    def Awake(self, message=None):
        self.key = 0

    #响铃时唤醒即可关闭响铃
    def Pause(self, message=None):
        self.key = 0
       
    def Text(self, message):
        voice = message['Data']
        if type(voice)==type(""):
            #语句里的我替换为主人
            voice= voice.replace("我", "主人")
            Triggers = ["取消提醒","关闭提醒"]
            #取消闹钟
            if any(map(lambda w: voice.__contains__(w), Triggers)):
                if del_remind.del_remind(self.timelist,self.say,self.listen):
                    #写入闹钟
                    write_read.clock(self.timelist)
            else:

                try:
                    voice = todat_time_analysis.todat_time_analysis().main(voice)
                except:
                    self.say("你可以这样设置,提醒你上午.下午.明天.每天.的哪个时间点或者提醒多少小时后")
                    return
                #解析的结果 {1: [1585647924, '提醒主人1个小时']}
                print("解析的结果",voice)
                if type({}) != type(voice):
                    return
                if not voice:
                    self.say("你可以这样设置,提醒你上午.下午.明天.每天.的哪个时间点或者提醒多少小时后")
                    return

                for x in voice:
                    if x==1:
                        #时间不可以低于现在时间戳
                        print("时间对比",voice[1][0],time.time())
                        if voice[1][0]>time.time():
                            #添加闹钟到闹钟队列
                            self.timelist.append(voice)
                            #写入闹钟
                            write_read.clock(self.timelist)
   
                            say_dtat = "设置成功,"+time.strftime( "%Y-%m-%d %H点%M分%S秒", time.localtime(voice[1][0]) ) + voice[1][1]
                            say_dtat = say_dtat.replace("00分",'',1).replace("00秒",'',1) 
                            
                        else:
                            say_dtat = "时间已经失效,请重新设置"

                    elif x ==0:
                        say_dtat = "设置成功,每天"+str(voice[0][0])+"点"+str(voice[0][1])+"分"+str(voice[0][3])
                        say_dtat = say_dtat.replace("00分",'',1)
                        #添加闹钟到闹钟队列
                        self.timelist.append(voice)
                        #写入闹钟
                        write_read.clock(self.timelist)


                self.say(say_dtat)






                    # if y==2:
                    #     xs_xf_xm = time.time()

                    #     xn = time.strftime("%Y", time.localtime(xs_xf_xm)) 
                    #     xy = time.strftime("%m", time.localtime(xs_xf_xm))
                    #     xr = time.strftime("%d", time.localtime(xs_xf_xm)) 
                    #     xs = time.strftime("%H", time.localtime(xs_xf_xm)) 
                    #     xf = time.strftime("%M", time.localtime(xs_xf_xm))
                    #     xm = time.strftime("%S", time.localtime(xs_xf_xm)) 

                    #     if  xn ==x[2][0] and xy ==x[2][1] and xr ==x[2][2] and xs ==x[2][3] and xf ==x[2][4] and xm ==x[2][5]:
                    #         self.send(MsgType=MsgType.Text, Receiver="SpeechSynthesis", Data="闹钟"+x[0][3])
                    #         self.send(MsgType=MsgType.Text, Receiver="Screen", Data="闹钟"+x[0][3])
                    #         print(self.timelist[number])
                    #         self.timelist.pop(number)
                    #         print(self.timelist)
                    #         #写入闹钟
                    #         write_read.clock(self.timelist)
                    #         self.key = 1
                    #         time.sleep(0.7)#让这一秒过去,让条件不成立
                    



                    
                    # elif x ==2:

                    #     say_dtat = "设置成功,"+str(voice[2][0])+"年"+str(voice[2][1])+"月"+str(voice[2][2])+"日"+str(voice[2][3])+"点"+str(voice[2][4])+"分"+str(voice[2][6])
                    #     say_dtat = say_dtat.replace("00分",'',1)
                    #     #添加闹钟到闹钟队列
                    #     self.timelist.append(voice)
                    #     #写入闹钟
                    #     write_read.clock(self.timelist)
                    



